﻿using EnetaMvc.Core.Domain.News;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;
using NHibernate;
using NHibernate.Criterion;
using System.Diagnostics;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class ArticleRepository : BaseRepository, IArticleRepository
    {
        private readonly ISession _session;

        public ArticleRepository(IMapperSession session) : base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
            Debug.WriteLine("NH hash: " + _session.GetHashCode());
        }

        public PagedResult<Article> ListPublishedArticles(int page, int pageSize)
        {
            var criteria = _session.CreateCriteria<Article>();
            criteria.CreateCriteria("PublishState")
                    .Add(Expression.Eq("IsVisibleOnPublicSite", true));

            return GetPagedResultForQuery<Article>(criteria, page, pageSize);
        }


        public Article GetPublishedArticleById(long id)
        {
            var article = GetArticleById(id);
            if (article.PublishState == null)
                return null;
            if (!article.PublishState.IsVisibleOnPublicSite)
                return null;

            return article;
        }

        public Article GetArticleById(long id)
        {
            return _session.Get<Article>(id);
        }


        public void SaveArticle(Article article)
        {
            if (article == null)
                return;

            SaveInTransaction(article);
        }
    }
}
